package com.shouer.doc.ui.main.presenter;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.shouer.doc.common.ShouerConst;
import com.shouer.doc.dao.AdviceReadRecord;
import com.shouer.doc.dao.AdviceReadRecordDao;
import com.shouer.doc.dao.DaoSession;
import com.shouer.doc.request.GsonRequest;
import com.shouer.doc.request.RequestUtil;
import com.shouer.doc.ui.main.response.QueryDocAdResponse;
import com.shouer.doc.ui.main.view.IMainView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by YYY-Work on 2017/5/24.
 */

public class MainPresenterImpl implements IMainPresenter{

    private IMainView mainView;

    public MainPresenterImpl(IMainView mainView)
    {
        this.mainView=mainView;
        EventBus.getDefault().register(this);
    }

    @Override
    public void onDestroy()
    {
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void queryDocAdInfo() {
        Map<String, String> param = new HashMap<>();
        param.put("postionId","3");

        final GsonRequest<QueryDocAdResponse> request = new GsonRequest(ShouerConst.APP_SERVER_https,"queryAdvertList", QueryDocAdResponse.class, new Response.Listener<QueryDocAdResponse>() {

            @Override
            public void onResponse(QueryDocAdResponse response) {

                if (null!=response.getTopAdvertisement()&&null!=response.getTopAdvertisement().getAdvertisementId())
                {
                    String adId=response.getTopAdvertisement().getAdvertisementId();
                    String userId=mainView.getUserId();
                    DaoSession daoSession=mainView.getDaoSession();
                    AdviceReadRecordDao adviceReadRecordDao=daoSession.getAdviceReadRecordDao();
                    List<AdviceReadRecord> adviceReadRecords=adviceReadRecordDao.queryBuilder().where(AdviceReadRecordDao.Properties.UserId.eq(userId),AdviceReadRecordDao.Properties.AdvertisementId.eq(adId)).list();
                    if (null!=adviceReadRecords&&adviceReadRecords.size()>0)
                    {
                        response.getTopAdvertisement().setReaded(true);
                    }
                }
                EventBus.getDefault().post(response);

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });

        RequestUtil.sendRequest(mainView.getContext(), param, request);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(QueryDocAdResponse response)
    {
        if (response.getErrorCode()>=0)
        {
            mainView.queryDocAdSuccess(response);
        }
    }
}
